package com.github.aaronshan.functions.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.CaseInsensitiveMap;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

import java.util.Map;

/**
 * @Auther: GGbond
 * @Date: 2020/3/21 10:59
 * @Description:
 */
@Description(name = "get_json_object_by_keys", value = "_FUNC_(json, keys[]) "
        , extended = "Example:\n"
        + "  > SELECT _FUNC_(json_array, key1, key2, key3...) FROM src LIMIT 1;")
public class UDFGetJsonObjectOneByKeys extends UDF {
    private Text result = new Text();

    public UDFGetJsonObjectOneByKeys() {
    }

    //    public Text evaluate(Text json, String... params) {
//        try {
//            JSONObject jsonObject = JSONObject.parseObject(json.toString());
//            for (String param : params) {
//                if (jsonObject.containsKey(param)) {
//                    result.set(jsonObject.get(param) == null ? null : jsonObject.get(param).toString());
//                    break;
//                }
//            }
//            return result;
//        } catch (Exception e) {
//            return null;
//        }
//    }
    public Text evaluate(Text json, String... params) {
        try {
            Map<String, Object> dataOrg = (Map<String, Object>) JSON.parse(json.toString());
            Map<String, Object> data = new CaseInsensitiveMap();
            if (dataOrg != null) {
                data.putAll(dataOrg);
            }
            for (String param : params) {
                if (data.containsKey(param)) {
                    result.set(data.get(param) == null ? null : data.get(param).toString());
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
